package me.chenjp.tracker.core.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: Chenjp
 * @description: 这个人很懒, 没有留下任何注释
 * @create: 2019-05-03 13:15
 */
@Slf4j
public final class HttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    private static final int SOCKET_TIMEOUT = 20000;

    private static final int CONNECTION_TIMEOUT = 20000;

    private static PoolingHttpClientConnectionManager cm = null;

    private static RequestConfig requestConfig = null;

    private static SSLContext sslContext = null;

    private static ResponseHandler<String> responseHandler = null;

    private static HttpRequestRetryHandler retryHandler = null;

    private static final String USER_AGENT =
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36";

    private static final CloseableHttpClient HTTP_CLIENT;

    private HttpUtils() {
    }

    static {
        try {
            sslContext = SSLContexts.custom().setProtocol("TLS").build();
            sslContext.init(null, new TrustManager[]{new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[]{};
                }

                @Override
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            }}, new SecureRandom());
        } catch (Exception e) {
            logger.error("Unexpected error", e);
        }
        Registry<ConnectionSocketFactory> socketFactoryRegistry =
                RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.INSTANCE)
                        .register("https", new SSLConnectionSocketFactory(sslContext)).build();
        cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        // 将最大连接数增加到200
        cm.setMaxTotal(200);
        // 将每个路由基础的连接增加到20
        cm.setDefaultMaxPerRoute(20);

        requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIMEOUT)
                .setConnectTimeout(CONNECTION_TIMEOUT).setAuthenticationEnabled(false).build();

        responseHandler = (response) -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 400) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity, "UTF-8") : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        };

        retryHandler = new DelayHttpRequestRetryHandler(8, true);

        HTTP_CLIENT = buildHttpClient();
    }

    private static CloseableHttpClient buildHttpClient() {
        return HttpClients.custom().setConnectionManager(cm).setRetryHandler(retryHandler)
                .setUserAgent(USER_AGENT).build();
    }

    /**
     * do getFile
     *
     * @param url    request url
     * @param params request params
     * @return request result
     */
    public static String get(String url, Map<String, String> params) throws IOException {
        HttpGet httpGet = new HttpGet(formatGetUrl(url, params));
        httpGet.setConfig(requestConfig);
        return HTTP_CLIENT.execute(httpGet, responseHandler);
    }

    public static String get(String url, String params) throws IOException {
        HttpGet httpGet = new HttpGet(url.concat(params));
        // HttpGet httpGet = new HttpGet(URLEncoder.encode(url.concat(params), "UTF-8"));
        httpGet.setConfig(requestConfig);
        return HTTP_CLIENT.execute(httpGet, responseHandler);
    }


    public static String get(String url, Map<String, String> params, Map<String, String> headers)
            throws IOException {
        HttpGet httpGet = new HttpGet(formatGetUrl(url, params));
        httpGet.setConfig(requestConfig);
        // set headers
        if (headers != null) {
            for (Map.Entry<String, String> e : headers.entrySet()) {
                httpGet.setHeader(e.getKey(), e.getValue());
            }
        }
        return HTTP_CLIENT.execute(httpGet, responseHandler);
    }

    private static String formatGetUrl(String url, Map<String, String> params) throws IOException {
        String result = url;
        if (params != null) {
            List<NameValuePair> nameValuePairs = new ArrayList<>();
            for (Map.Entry<String, String> e : params.entrySet()) {
                NameValuePair namePair = new BasicNameValuePair(e.getKey(), e.getValue());
                nameValuePairs.add(namePair);
            }
            String str = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs));
            if (url.contains("?")) {
                result = url + "&" + str;
            } else {
                result = url + "?" + str;
            }
        }
        return result;
    }

    public static String post(String url, Map<String, String> params, Map<String, String> headers)
            throws IOException {
        // set params
        UrlEncodedFormEntity entity = null;
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        if (params != null) {
            for (Map.Entry<String, String> e : params.entrySet()) {
                NameValuePair namePair = new BasicNameValuePair(e.getKey(), e.getValue());
                nameValuePairs.add(namePair);
            }
            entity = new UrlEncodedFormEntity(nameValuePairs, Consts.UTF_8);
        }
        return post(url, entity, headers);
    }

    public static String post(String url, HttpEntity entity, Map<String, String> headers)
            throws IOException {
        // 设置参数
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        // set headers
        if (headers != null) {
            for (Map.Entry<String, String> e : headers.entrySet()) {
                httpPost.setHeader(e.getKey(), e.getValue());
            }
        }
        // set params
        httpPost.setEntity(entity);
        return HTTP_CLIENT.execute(httpPost, responseHandler);
    }

    public static String post(String url, String jsonBody, Map<String, String> headers)
            throws IOException {
        // 设置参数
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        // set headers
        if (headers != null) {
            for (Map.Entry<String, String> e : headers.entrySet()) {
                httpPost.setHeader(e.getKey(), e.getValue());
            }
        }
        // set params
        if (StringUtils.isNotBlank(jsonBody)) {
            StringEntity entity = new StringEntity(jsonBody, ContentType.APPLICATION_JSON);
            entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
            httpPost.setEntity(entity);
        }
        return HTTP_CLIENT.execute(httpPost, responseHandler);
    }

    public static String requestDelete(String url, Map<String, String> headers) throws IOException {
        // 设置参数
        HttpDelete httpDelete = new HttpDelete(url);
        httpDelete.setConfig(requestConfig);
        // set headers
        if (headers != null) {
            for (Map.Entry<String, String> e : headers.entrySet()) {
                httpDelete.setHeader(e.getKey(), e.getValue());
            }
        }
        return HTTP_CLIENT.execute(httpDelete, responseHandler);
    }

    public static String upload(String url, InputStream input, String fileName,
                                Map<String, String> headers) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        //InputStreamBody body = new InputStreamBody(in, ContentType.MULTIPART_FORM_DATA, fileName);
        IOUtils.copy(input, output);
        ByteArrayBody body =
                new ByteArrayBody(output.toByteArray(), ContentType.MULTIPART_FORM_DATA, fileName);
        HttpEntity httpEntity = MultipartEntityBuilder.create().addPart("file", body).build();
        return post(url, httpEntity, headers);
    }

    public static boolean download(String url, String filePath, Map<String, String> params)
            throws IOException {
        HttpGet httpGet = new HttpGet(formatGetUrl(url, params));
        httpGet.setConfig(requestConfig);
        // download
        HttpResponse httpResponse = HTTP_CLIENT.execute(httpGet);
        HttpEntity entity = httpResponse.getEntity();
        if (entity.getContentLength() <= 0) {
            return false;
        }
        // write the inputStream to a FileOutputStream
        File file = new File(filePath);
        if (file.exists()) {
            boolean isDeleted = file.delete();
            if (!isDeleted) {
                logger.warn("Error to delete file, path={}", filePath);
            }
        }
        org.apache.commons.io.FileUtils.copyInputStreamToFile(entity.getContent(), file);
        return true;
    }

    public static HttpResponse download(String url, Map<String, String> params) throws IOException {
        HttpGet httpGet = new HttpGet(formatGetUrl(url, params));
        httpGet.setConfig(requestConfig);
        // download
        return HTTP_CLIENT.execute(httpGet);
    }

    static class DelayHttpRequestRetryHandler extends DefaultHttpRequestRetryHandler {

        private static final Logger logger =
                LoggerFactory.getLogger(DelayHttpRequestRetryHandler.class);
        private static final Integer DEFAULT_DELAY_SECONDS = 3;

        /**
         * Default constructor
         */
        protected DelayHttpRequestRetryHandler(final int retryCount,
                                               final boolean requestSentRetryEnabled) {
            super(retryCount, requestSentRetryEnabled);
        }

        @Override
        public boolean retryRequest(IOException exception, int executionCount,
                                    HttpContext context) {
            boolean isRetry = super.retryRequest(exception, executionCount, context);
            if (isRetry) {
                try {
                    logger.info("Retry request will be delay,exception={},executionCount={}",
                            exception, executionCount);
                    TimeUnit.SECONDS.sleep(DEFAULT_DELAY_SECONDS);
                } catch (InterruptedException e) {
                    logger.error("DelayHttpRequestRetryHandler error", e);
                }
            }
            return isRetry;
        }
    }


    /**
     * Gets remote ip.
     *
     * @param request the request
     * @return the remote ip
     */
    public static String getRemoteIP(HttpServletRequest request) {
        String ip;
        if (request.getHeader("x-forwarded-for") == null) {
            ip = request.getRemoteAddr();
        } else {
            ip = request.getHeader("x-forwarded-for");
        }
        log.info("请求源 ip: {}", ip);
        try {
            ip = ip.split(",")[0];
        } catch (Exception e) {
            e.printStackTrace();
            ip = "116.22.135.82";
        }

        return ip;
    }
}